package com.xunge.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xunge.mapper.CourseMapper;
import com.xunge.pojo.Course;
import com.xunge.pojo.CourseQueryParam;
import com.xunge.pojo.PageResult;
import com.xunge.pojo.Result;
import com.xunge.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    /**
     * 分页查询课程信息
     */
    @Override
    public PageResult<Course> page(CourseQueryParam courseQueryParam) {
        // 设置分页参数
        PageHelper.startPage(courseQueryParam.getPage(), courseQueryParam.getPageSize());
        // 执行查询
        Page<Course> page = (Page<Course>) courseMapper.list(courseQueryParam.getName(), courseQueryParam.getCode(), courseQueryParam.getStatus());
        // 封装分页结果
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    /**
     * 新增课程
     */
    @Override
    public void save(Course course) {

        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    /**
     * 根据ID查询课程
     */
    @Override
    public Course getById(Integer id) {
        return courseMapper.getById(id);
    }

    /**
     * 根据ID修改课程
     */
    @Override
    public void update(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }

    /**
     * 根据ID删除课程
     */
    @Override
    public void deleteById(Integer id) {
        courseMapper.deleteById(id);
    }

    /**
     * 批量删除课程
     */
    @Override
    public Result delete(List<Integer> ids) {
        List<Integer> relatedIds = new ArrayList<>();
        // 检查每个课程是否可以删除
        for (Integer courseId : ids) {
            if (!canDelete(courseId)) {
                relatedIds.add(courseId);
            }
        }
        // 如果有课程无法删除，则返回错误信息
        if (!relatedIds.isEmpty()){
            if (relatedIds.size() == 1){
                String relations = getCourseRelations(relatedIds.get(0));
                Course course = getById(relatedIds.get(0));
                return Result.error("课程名称为【" + course.getName() + "】无法删除，存在关联数据:" + relations);
            }
            List<String> courseNames = courseMapper.getNamesByIds(relatedIds);
            return Result.error("课程名称为 " + courseNames + " 无法删除，存在关联数据");
        }
        courseMapper.deleteByIds(ids);
        return Result.success();
    }

    /**
     * 查询所有课程
     */
    @Override
    public List<Course> listAll() {
        return courseMapper.listAll();
    }

    @Override
    public boolean isNameExists(String name, Integer excludeId) {
        if (excludeId == null) {
            // 新增时检查
            return courseMapper.countByName(name) > 0;
        } else {
            // 编辑时检查，排除当前记录
            Course existingCourse = courseMapper.findByName(name, excludeId);
            return existingCourse != null;
        }
    }

    @Override
    public boolean isCodeExists(String code, Integer excludeId) {
        if (excludeId == null) {
            // 新增时检查
            return courseMapper.countByCode(code) > 0;
        } else {
            // 编辑时检查，排除当前记录
            Course existingCourse = courseMapper.findByCode(code, excludeId);
            return existingCourse != null;
        }
    }

    @Override
    public boolean canDelete(Integer courseId) {
        // 检查各个关联表的使用情况
        int clazzCourseCount = courseMapper.countClazzCourseUsage(courseId);// 班级课程关联表
        int attendanceCount = courseMapper.countAttendanceUsage(courseId);// 考勤关联表
        int examCount = courseMapper.countExamUsage(courseId);// 考试关联表
        int homeworkCount = courseMapper.countHomeworkUsage(courseId);// 作业关联表
        int gradeCount = courseMapper.countGradeUsage(courseId);// 成绩关联表
        
        // 如果任何一个关联表有数据，则不能删除
        return clazzCourseCount == 0 && attendanceCount == 0 && 
               examCount == 0 && homeworkCount == 0 && gradeCount == 0;
    }

    @Override
    public String getCourseRelations(Integer courseId) {
        StringBuilder relations = new StringBuilder();
        
        int clazzCourseCount = courseMapper.countClazzCourseUsage(courseId);
        int attendanceCount = courseMapper.countAttendanceUsage(courseId);
        int examCount = courseMapper.countExamUsage(courseId);
        int homeworkCount = courseMapper.countHomeworkUsage(courseId);
        int gradeCount = courseMapper.countGradeUsage(courseId);
        
        if (clazzCourseCount > 0) {
            relations.append("班级课程关联(").append(clazzCourseCount).append("条), ");
        }
        if (attendanceCount > 0) {
            relations.append("考勤记录(").append(attendanceCount).append("条), ");
        }
        if (examCount > 0) {
            relations.append("考试安排(").append(examCount).append("条), ");
        }
        if (homeworkCount > 0) {
            relations.append("作业安排(").append(homeworkCount).append("条), ");
        }
        if (gradeCount > 0) {
            relations.append("成绩记录(").append(gradeCount).append("条), ");
        }
        
        if (relations.length() > 0) {
            // 移除最后的逗号和空格
            relations.setLength(relations.length() - 2);
        }
        
        return relations.toString();
    }
} 